package com.cyber.parkingremotev2;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SettingActivity extends Activity {

	public final static int M_REQUIRE = 21;
	public final static int M_SEND_ACK = 22;
	public final static String M_SEQ = "seq";
	public final static String M_TYPE = "type";
	public final static String M_VALUE = "value";
	Communication.ComBinder mComBinder;
	FileService.FileBinder mFileBinder;
	Button mButtonQuery;
	Button mButtonSend;
	Button mButtonLoad;
	Button mButtonSave;
	Button mButtonRemoteLoad;
	Button mButtonRemoteSave;
	TextView mText;
	ArrayList<Integer> mFieldArray;
	static int mFieldCount;
	CommandSystem commandSystem;
	SimpleAdapter mTableFieldAdapter;
	TableLayout mTableLayout;
	HashMap<Integer, EditText> mFieldMap = new HashMap<Integer, EditText>();

	int mRequireId = 1;

	public static int getFieldCount() {
		return mFieldCount - 1;
	}

	private String getAllEncodedFieldsFromTable() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < CommandSystem.CS_MAX_COMMAND; ++i) {
			sb.append(getFieldRowFromTable(i + 1) + "\n");
		}
		return sb.toString();
	}

	private String getFieldRowFromTable(int seq) {
		int index = getIndex(seq, 1);
		ArrayList<Integer> parameters = new ArrayList<Integer>();
		for (int i = 0; i < mFieldCount; ++i) {
			EditText et = mFieldMap.get(index + i);
			int value = Integer.valueOf(et.getText().toString());
			parameters.add(value);
		}
		return commandSystem.getParameter(seq, parameters);
	}

	private void createTable() {
		Resources res = getResources();
		String[] fields = res.getStringArray(R.array.field_array);
		mFieldCount = fields.length;
		LayoutInflater inflater = LayoutInflater.from(this);
		mTableLayout = (TableLayout) findViewById(R.id.setting_table);
		TableRow rowHeader = (TableRow) inflater.inflate(R.layout.setting_row,
				null);

		for (int i = 0; i < mFieldCount; ++i) {
			TextView header = (TextView) inflater.inflate(
					R.layout.table_header, null);
			header.setText(fields[i]);
			rowHeader.addView(header);
		}
		mTableLayout.addView(rowHeader);
		for (int j = 0; j < CommandSystem.CS_MAX_COMMAND; ++j) {
			TableRow rowField = (TableRow) inflater.inflate(
					R.layout.setting_row, null);
			for (int i = 0; i < mFieldCount; ++i) {
				EditText field = (EditText) inflater.inflate(
						R.layout.table_item, null);
				if (i == 0) {
					field.setText(String.valueOf(j + 1));
				}
				rowField.addView(field);
				mFieldMap.put(j * mFieldCount + i, field);
			}
			mTableLayout.addView(rowField);
		}

	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		commandSystem = new CommandSystem();
		setContentView(R.layout.activity_setting);
		mButtonQuery = (Button) findViewById(R.id.button21);
		mButtonQuery.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				send(commandSystem.require(mRequireId));
				mRequireId++;
				if (mRequireId > CommandSystem.CS_MAX_COMMAND) {
					mRequireId = 1;
				}
			}

		});
		mButtonSend = (Button) findViewById(R.id.button22);
		mButtonSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				send(getAllEncodedFieldsFromTable());
			}

		});
		mButtonLoad = (Button) findViewById(R.id.button23);
		mButtonLoad.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}

		});
		mButtonSave = (Button) findViewById(R.id.button24);
		mButtonSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// FIXME
				writeFile(getFileName(), getAllEncodedFieldsFromTable());
			}

		});
		
		mButtonRemoteSave = (Button)findViewById(R.id.button25);
		mButtonRemoteSave.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				send(commandSystem.save());
			}
			
		});
		mText = (TextView) findViewById(R.id.textView21);
		// mGridHeader = (GridView) findViewById(R.id.gridView21);
		// mGridField = (GridView) findViewById(R.id.gridView22);
		mFieldCount = 0;
		createTable();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_setting, menu);
		return true;
	}

	protected void onStart() {
		super.onStart();
		Intent bindComIntent = new Intent(this, NetCommunication.class);
		bindService(bindComIntent, mComConnection, Context.BIND_AUTO_CREATE);
		Intent bindFileIntent = new Intent(this, FileService.class);
		bindService(bindFileIntent, mFileConnection, Context.BIND_AUTO_CREATE);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_control:
			Intent intent = new Intent();
			setResult(RESULT_OK, intent);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void writeFile(String fileName, String data) {
		if (mFileBinder != null) {
			mFileBinder.writeFile(fileName, data);
		}
	}

	private void readFile(String fileName) {

	}

	private void processReadFile(String data) {

	}

	void connect(String target) {
		if (mComBinder != null)
			mComBinder.connect(target);
	}

	void send(String data) {
		if (mComBinder != null)
			mComBinder.sendData(data);
	}

	protected int getField(int seq, int type) {
		return 0;
	}

	private int getIndex(int seq, int type) {
		return (seq - 1) * mFieldCount + type;
	}

	protected void updateField(int seq, int type, int value) {
		int index = getIndex(seq, type);
		EditText ed = mFieldMap.get(index);
		ed.setText(String.valueOf(value));
		ed.setTextColor(Color.GREEN);
	}

	protected void compareField(int seq, int type, int value) {
		int index = getIndex(seq, type);
		EditText ed = mFieldMap.get(index);
		int old = Integer.valueOf(ed.getText().toString());
		if (old == value) {
			ed.setTextColor(Color.GREEN);
		} else {
			ed.setTextColor(Color.YELLOW);
		}

	}

	public static final String DIR = "/sdcard/";

	private String getFileName() {
		if (mComBinder != null) {
			return DIR + mComBinder.getName() + ".txt";
		} else {
			return "park.txt";
		}
	}

	private final Handler mUiHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case ParkRemoteActivity.M_GOT_DATA: {
				String content = msg.getData().getString(
						ParkRemoteActivity.M_TEXT);
				mText.setText(content);
			}
				break;
			case FileService.M_READ_OK: {
				// FIXME

			}
				break;
			case FileService.M_WRITE_OK: {
				// FIXME
				mText.setText("write ok");
			}
				break;
			case FileService.M_IO_ERROR: {
				mText.setText(msg.getData().getString(FileService.M_ERROR));
			}
				break;
			case M_REQUIRE: {
				int seq = msg.getData().getInt(M_SEQ);
				int type = msg.getData().getInt(M_TYPE);
				int value = msg.getData().getInt(M_VALUE);
				updateField(seq, type, value);
			}
				break;
			case M_SEND_ACK: {
				int seq = msg.getData().getInt(M_SEQ);
				int type = msg.getData().getInt(M_TYPE);
				int value = msg.getData().getInt(M_VALUE);
				compareField(seq, type, value);
			}
				break;
			default:
				break;
			}
		}

	};
	private final ServiceConnection mComConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			mComBinder = (Communication.ComBinder) arg1;
			mComBinder.setUiHandler(mUiHandler);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mComBinder = null;
		}
	};

	private final ServiceConnection mFileConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			mFileBinder = (FileService.FileBinder) arg1;
			mFileBinder.setUiHandler(mUiHandler);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mFileBinder = null;
		}
	};

}
